#include "makuai.h"
#include "onewire.h"
#include "ds1302.h"


unsigned char code k_n[4][4] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
unsigned char code shownumber[] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10,0xff,0xbf};
unsigned char code ds_read_arr_k[3] = {0x81,0x83,0x85};
unsigned char ds1302_time_k[3] = {0x00,0x25,0x23};
	
void Delay500us()		//@12.000MHz
{
	unsigned char i, j;

	i = 6;
	j = 211;
	do
	{
		while (--j);
	} while (--i);
}

	
void Delay(unsigned int c)		//@12.000MHz
{
	unsigned char i, j;
while(c--)
{
	i = 12;
	j = 169;
	do
	{
		while (--j);
	} while (--i);
}
}

void Latch(unsigned char p2,unsigned char p0)
{
	P2 = (P2 & 0x1f | p2);
	P0 = p0;
	P2 &= 0x1f;
}

unsigned char Key(void)
{
	static unsigned char k_i = 0,keycount = 0;
	P3 |= 0x3f;
	P3 &= ~(0x01<<k_i);
	if(key_lie_1 == 0){Delay(5);keycount++;if(keycount == 3){keycount = 0;return k_n[k_i][0];}}
	if(key_lie_2 == 0){Delay(5);keycount++;if(keycount == 3){keycount = 0;return k_n[k_i][1];}}
	if(key_lie_3 == 0){Delay(5);keycount++;if(keycount == 3){keycount = 0;return k_n[k_i][2];}}
	if(key_lie_4 == 0){Delay(5);keycount++;if(keycount == 3){keycount = 0;return k_n[k_i][3];}}
	k_i++;
	if(k_i == 4)
		k_i = 0;
	return 0;
}

void Nixie(unsigned char location,unsigned char number)
{
	Latch(NIXIE_D,0xff);
	Latch(NIXIE_W,0x01<<(location-1));
	Latch(NIXIE_D,shownumber[number]);
	Delay500us();
}

unsigned char Key_time(void)
{
	static unsigned char k_time = 0;
	P3 |= 0x3f;
	P3 &= ~(0x01<<k_time);
	if(key_lie_1 == 0){Delay(20);while(key_lie_1 == 0);Delay(20);if(key_lie_1 == 1)return k_n[k_time][0];}
	if(key_lie_2 == 0){Delay(20);while(key_lie_2 == 0);Delay(20);if(key_lie_2 == 1)return k_n[k_time][1];}
	if(key_lie_3 == 0){Delay(20);while(key_lie_3 == 0){read_ds();Nixie(1,21);Nixie(2,2);Nixie(4,ds1302_time_k[1]/16);Nixie(5,ds1302_time_k[1]%16);Nixie(7,ds1302_time_k[0]/16);Nixie(8,ds1302_time_k[0]%16);};Delay(20);if(key_lie_3 == 1)return k_n[k_time][2];}
	if(key_lie_4 == 0){Delay(20);while(key_lie_4 == 0);Delay(20);if(key_lie_4 == 1)return k_n[k_time][3];}
	k_time++;
	if(k_time == 4)
		k_time = 0;
	return 0;
}


